<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin\AdminUsers;
use App\Models\Tokens;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

class LoginQywxController extends BaseController
{
    private $log;

    public function __construct()
    {
        $this->log = new Logger('qywx');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path() . '/logs/qywx.log', 3, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
    }

    public function index(Request $request)
    {
//        return $this->returnMsg(100, '您首次使用企业微信登陆,请绑定你的后台账号', [
//            'redirectPath' => '/loginold',
//            'avatar' => base64_encode('aa'),
//            'userid' => 123
//        ]);
        if ($request->has('code') && !empty($request->get('code'))) {
//            回调code换取数据
            $code = $request->get('code');
            $accessToken = $this->getAccessToken();
//            获取访问用户身份,https://developer.work.weixin.qq.com/document/path/91023
            $data = $this->getUserInfo($code, $accessToken);
//            $this->log->info('用户信息:' . json_encode($data) . ';acc:' . $accessToken);
//            非企业成员,没有user_ticket只有openid
            if (!isset($data['user_ticket'])) {
                return $this->returnMsg(100, '非企业成员,不能授权登陆', [
                    'redirectPath' => '/loginold'
                ]);
            }
            $ticket = $data['user_ticket'];
            $data = $this->getUserDetail($ticket, $accessToken);
//            $this->log->info('具体信息:' . json_encode($data));
//            获取企业微信会员信息,进行登陆操作
            return $this->loginCheck($data, $request->getClientIp());
        } else {
            $config = config('qywx');
            $data['url'] = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $config['corpid'] . '&redirect_uri=' . urlencode($config['CodeBackUrl']) . '&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid=' . $config['AgentId'] . '&state=#wechat_redirect';
            return $this->returnMsg(200, '生成成功', $data);
        }
    }

    /*
     * {
       "errcode": 0,
       "errmsg": "ok",
       "userid":"lisi",
       "gender":"1",
       "avatar":"http://shp.qpic.cn/bizmp/xxxxxxxxxxx/0",
       "qr_code":"https://open.work.weixin.qq.com/wwopen/userQRCode?vcode=vcfc13b01dfs78e981c",
       "mobile": "13800000000",
       "email": "zhangsan@gzdev.com",
       "biz_mail":"zhangsan@qyycs2.wecom.work",
       "address": "广州市海珠区新港中路"
    }
     */
    protected function loginCheck($data, $clientIp = '')
    {
        $ModelUsers = new AdminUsers();
        $where = ['qywx_userid' => $data['userid']];
        $fields = ['id', 'user_name', 'shop_id', 'role_id', 'dept_id', 'supervisor_id', 'user_type', 'agent_id', 'position_id', 'avatar', 'login_fail_num', 'status', 'del_flag'];
        $res = $ModelUsers->where($where)->select($fields)->first();
        if (empty($res)) {
//            新账号,要传回给前端进行账号密码登陆后绑定
            return $this->returnMsg(100, '您首次使用企业微信登陆,请绑定你的后台账号', [
                'redirectPath' => '/loginold',
                'avatar' => base64_encode($data['avatar']),
                'userid' => $data['userid']
            ]);
        }
        if ($res->status != 0 || $res->del_flag == 2) {
            return $this->returnMsg(100, '您已被停用后台账号,请让管理员开通', [
                'redirectPath' => '/loginold'
            ]);
        }
//        更新token
        $days_time = date('Y-m-d H:i:s') . 'sltx@';
        $payload = array('id' => $res->id, 'user_id' => $res->id, 'time' => $days_time, 'role_id' => $res->role_id);
        $token = getTokenById($payload);
        $uparr = ['user_id' => $res->id];
        $uparr['user_name'] = $res->user_name;
        $uparr['login_ip'] = $clientIp;
        $uparr['role_id'] = $res->role_id;
        $uparr['token'] = $token;
        if (Tokens::where(['user_id' => $res->id])->count('id') <= 0) {
            Tokens::insert($uparr);
        } else {
            Tokens::where(array('user_id' => $res->id))->update($uparr);
        }
//        更新会员数据
        $upData = [
            'login_ip' => $clientIp,
            'update_time' => date('Y-m-d H:i:s'),
            'online' => 1,
            'login_fail_num' => 0
        ];
        if (empty($res->avatar)) {
            $upData['avatar'] = $data['avatar'];
        }
        $ModelUsers->where(['id' => $res->id])->update($upData);
        $data = $res->toArray();
        $data['token'] = $token;
        return $this->returnMsg(200, '登陆成功', $data);
    }

    protected function getAccessToken()
    {
        $config = config('qywx');
        $apiUrl = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' . $config['corpid'] . '&corpsecret=' . $config['Secret'];
        $response = Http::withOptions([
//            'debug' => true,
            'timeout' => 30,
            'connect_timeout' => 30,
            'read_timeout' => 30
        ])->get($apiUrl);
        $data = $response->json();
        return $data['access_token'] ?? '';
    }

//https://developer.work.weixin.qq.com/document/path/91023
    protected function getUserInfo($code, $accessToken)
    {
        $apiUrl = 'https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=' . $accessToken . '&code=' . $code;
        $response = Http::withOptions([
//            'debug' => true,
            'timeout' => 30,
            'connect_timeout' => 30,
            'read_timeout' => 30
        ])->get($apiUrl);
        $data = $response->json();
        return $data;
    }

//    获取访问用户敏感信息,https://developer.work.weixin.qq.com/document/path/95833
    protected function getUserDetail($userTicket, $accessToken)
    {
        $apiUrl = 'https://qyapi.weixin.qq.com/cgi-bin/auth/getuserdetail?access_token=' . $accessToken;
        $response = Http::withOptions([
//            'debug' => true,
            'timeout' => 30,
            'connect_timeout' => 30,
            'read_timeout' => 30
        ])->withHeaders([
            'Accept' => 'application/json',
            'Content-Type' => 'application/json;charset=utf-8'
        ])->post($apiUrl, ['user_ticket' => $userTicket]);
        return $response->json();
    }
}
